package com.firexxx.vp.application.thread;

import com.firexxx.vp.application.StbCommandService;
import com.firexxx.vp.application.dto.StbDto;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/02/15 20:15
 */
@Component
@Slf4j
@Data
public class StbRegisterThread extends Thread implements InitializingBean {

    @Value("${register.queue.size}")
    private int registerQueueSize;

    private ArrayBlockingQueue<StbDto> queue;

    @Autowired
    private StbCommandService stbCommandService;

    private final static String TRACE_UUID = "trace_uuid";

    @Override
    public void run() {
        while (true) {
            if (queue.isEmpty()) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                continue;
            }

            StbDto stbDto = queue.poll();
            MDC.put(TRACE_UUID, stbDto.getTraceId());

            try {
                stbCommandService.register(stbDto);
            } catch (Throwable throwable) {
                log.error("机顶盒{}声纹注册服务异常{}", stbDto, throwable);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.queue = new ArrayBlockingQueue<>(registerQueueSize);

        this.start();
    }
}